import axios from "axios";
import { ElMessage } from 'element-plus'
import NProgress from "nprogress" //轻量级进度条库
import "nprogress/nprogress.css"
import errorCode from "./errorCode"
import { useUser } from "../store/user";
import router from "../router";
const userStore = useUser()

// const open = () => {
//   ElMessage('This is a message.')
// }
const request = axios.create({
  // 基础路径上会携带这个
  baseURL: '',
  timeout: 5000,
})
request.interceptors.request.use(config => {
  const token = userStore.token
  if (token) {
    config.headers['X-Authorization'] = token

  } else {
    // 拦截到登录页面
  }
})

// HTTPresponse拦截
request.interceptors.response.use(res => {
  NProgress.done()
  const status = Number(res.status) || 200
  const statusmessage = res.data.msg || errorCode[status] || errorCode["default"]
  // 后台定义 424 针对令牌过去的特殊响应码
  if (status === 424 || status === 401) {
    message.error('令牌状态已过期，请点击重新登录')
    userStore.LogOut().then(() => {
      // 刷新登录页面，避免多次弹框
      window.location.reload()
    })
    return
  }
  if (status !== 200 || res.data.code === 1) {
    if (statusmessage.includes('账号锁定') || statusmessage.includes('账号登录过期') || statusmessage.includes('账号删除') || statusmessage.includes('运营账号已过期')) {
      message.error(statusmessage)
      if (router.currentRoute.value.path !== '/login') {
        setTimeout(() => {
          window.location.reload()
        }, 1500)
        sessionStorage.clear()
        REMOVE_TOKEN()
      }
      return
    } else {
      message.error(statusmessage)
      return Promise.reject(new Error(statusmessage))
    }
  }
  return res.data
}),
  error => {
    NProgress.done()
    // message.error(error.response.data.msg)
    if (error.response.status == 401) {
      // message.error('用户名或密码错误', 3)
    }
    console.log('errorerror', error)
    if (error.response.status == 424) {
      message.error('令牌状态已过期，3秒后重新登录', 3)
      let userStore = useUserStore()
      userStore.LogOut().then(() => {
        // 刷新登录页面，避免多次弹框
        window.location.reload()
      })
      return error.response.data.msg
    } else {
      message.error(`${error.response.data.msg}`)
    }
    return Promise.reject(error)
  }







//对外暴露
export default request